var apps = getApp();

/*************************/
/*****自写API方法集成******/
/*************************/

/*
*封装页面跳转API
*url为跳转目标页，types为跳转方式，data为所页面传递数据（可选，对象方式）
*types取值范围：n-wx.navigateTo;d-wx.redirectTo;s-wx.switchTab;
*ln-n方式的扩展，可以自动判断是否需要登录才能跳转，ld功能相同
*/
function nav(url,types,data) {
  data = data || ''; 
  if (data==''){
    //不带参数的跳转
    if (types == 'n') {
      wx.navigateTo({
        url: url
      })
    } else if (types == 'd') {
      wx.redirectTo({
        url: url,
      })
    } else if (types == 's') {
      wx.switchTab({
        url: url
      })
    } else if (types == 'ln') {
      if (loginFirst()) {
        wx.navigateTo({
          url: url
        })
      }

    } else if (types == 'ld') {
      if (loginFirst()) {
        wx.redirectTo({
          url: url,
        })
      }
    }
  }else{
    //带参数的跳转
    var param;
    var num = 0;
    for (var obj in data) {
      if(num==0){
        param = obj + '=' + data[obj];
      }else{
        param = param + '&' + obj + '=' + data[obj];
      }
      num++;
    }
    console.log(param)
    //进行跳转操作
    if (types == 'n') {
      wx.navigateTo({
        url: url + '?' + param
      })
    } else if (types == 'd') {
      wx.redirectTo({
        url: url + '?' + param
      })
    } else if (types == 's') {
      wx.switchTab({
        url: url + '?' + param
      })
    } else if (types == 'ln') {
      if (loginFirst()) {
        wx.navigateTo({
          url: url + '?' + param
        })
      }

    } else if (types == 'ld') {
      if (loginFirst()) {
        wx.redirectTo({
          url: url + '?' + param
        })
      }
    }
  }
  
  
}

/* 
*封装登录模块，默认获取用户公开信息等
*使用必须配合现有模块集成的PHP和数据库文件
*两个参数都为必选，num为手机号，fn为回调函数
*不需要手机号登录时，手机号可以写为num=''
*/
function login(num,fn,that){
  wx.showToast({
    title: '登录中',
    icon: 'loading',
    duration: 2000
  })

  wx.login({
    success: function (e) {
      var path = 'Personal/login';
      var data = {
        code: e.code
      }
      request(path, data, false, (res)=>{
        console.log(res);
        console.log(213243);
        if (res.data.status == 'Success') {
          getUserInfo(res.data.trd_session,num,fn);
        } else if (res.data.status == 'Fail') {
          wx.showModal({
            title: '登录失败',
            content: '服务器繁忙，请稍后再试！',
            showCancel: false
          })
        }
        if (that) {
          that.setData({
            islog: 2,
          })
        }
      });
    },
    fail: function (e) {
      console.log(e)
      // fail
      wx.showModal({
        title: '提示',
        content: '登录失败，请检查网络并重试！',
        showCancel: false
      })
    },
    complete: function (e) {
      if(that){
        that.setData({
          islog: 2,
        })
      }
    }
  })
}

function getUserInfo(trd_session,num,fn){
  var that = this;
  wx.getUserInfo({
    success: function (res) {
      var path = 'Personal/setUserInfo';
      //判断是否有手机号登录
      if (num == '') {
        var data = {
          rawData: res.rawData,
          signature: res.signature,
          encryptedData: res.encryptedData,
          iv: res.iv,
          trd_session: trd_session
        }
      }else{
        var data = {
          rawData: res.rawData,
          signature: res.signature,
          encryptedData: res.encryptedData,
          iv: res.iv,
          trd_session: trd_session,
          phonum: num
        }
      }
      request(path, data, false, (res)=>{
        if (res.data.status == "success") {
          fn(res)
        } else {
          console.log(res)
          wx.showModal({
            title: '登录失败',
            content: '服务器繁忙，请稍后重试！',
            showCancel: false
          })
        }
      })
    },
    fail: function () {
      wx.showModal({
        title: '登录失败',
        content: '系统繁忙，请稍后重试！',
        showCancel: false
      })
    }
  })
}

/*
*封装弹出框提示API组件，分别为showToast，showLoading，showModal；对应取值为s、l、m
*当为showToast时，types、content、title为必选，其他不选，其中title取值为s-success;l-loading
*当为showLoading时，只有types为必选，content为可选，其他不选，content为提示内容，不选默认显‘加载中’
*当为showModal时，types、content为必选，其他为可选，title默认值为‘提示’，fn返回用户选择结果，true为确定，false为取消
*duration默认为2000毫秒
*/
function toast(types, content, title, duration,fn){
  title = title || '提示'; 
  duration = duration || 2000;
  content = content || '加载中';
  fn = fn || '';
  if (title=='s'){
   title='success';
  } else if (title == 'l'){
    title = 'loading';
  }
  //开始判断交互类型
  if (types=='t'){
    wx.showToast({
      title: content,
      icon: title,
      duration: duration
    })
  } else if (types == 'l'){
    wx.showLoading({
      title: content,
    })
  } else if (types == 'm') {
    if (fn==''){
      //没有回调的modal
      wx.showModal({
        title: title,
        content: content,
        showCancel:true
      })
    }else{
      wx.showModal({
        title: title,
        content: content,
        success: function (res) {
          if (res.confirm) {
            fn(res.confirm);
          } else if (res.cancel) {
            fn(!(res.cancel));
          }
        }
      })
    }
    
  }

}
/*
*网络请求API封装
*参数全部为必选参数
*path格式为：控制器名/方法名，data为传递的数据对象，默认不需要添加appkey等数据
*islogin取值为true或false，用于确定是否为用户登录状态的网络请求
*当islogin取值为true时，会默认发送appkey和trd_session数据，并对用户登录状态进行自动验证
*当islogin取值为false时，会默认只发送appkey，不对用户登录状态做任何验证，用于通用请求
*/
function request(path, data, islogin, fn) {
  var url = apps.globalData.adminUrl + path;
  var trd_session = apps.globalData.openUserInfo;
  data.appkey = apps.globalData.appKey;
  data.app_vision = apps.globalData.appVision;
  
  if (islogin) {
    
    if (loginFirst()) {
      data.trd_session = trd_session;
      wx.request({
        url: url,
        data: data,
        method: 'GET',
        success: function (res) {
            getResLogin(res.data);
            fn(res);
        },
        fail: function (res) {
          //调用接口失败或回传失败
          wx.showModal({
            title: '服务器繁忙',
            content: '服务器繁忙，请稍后再试！',
            success: function (res) {
              if (res.confirm) {
                wx.switchTab({
                  url: '/pages/Personal/index/index'
                })
              }
            }
          })
        },
        complete: function(res){
          
        },
      })
    }
  }else{
    console.log(url);
    console.log(13131);
    wx.request({
      url: url,
      data: data,
      method: 'GET',
      success: function (res) {
          getRes(res.data);
          fn(res);
      },
      fail: function (res) {
        //调用接口失败或回传失败
        wx.showModal({
          title: '服务器繁忙',
          content: '网络不稳定，请稍后再试！',
          success: function (res) {
            if (res.confirm) {
              wx.switchTab({
                url: '/pages/Personal/index/index'
              })
            }
          }
        })
      },
      complete: function (res) {
        console.log(res);
      },
    })
  } 
}

/*
*网络上传API封装
*参数全部为必选参数
*path格式为：控制器名/方法名，data为传递的数据对象，默认不需要添加appkey等数据
*islogin取值为true或false，用于确定是否为用户登录状态的网络请求
*当islogin取值为true时，会默认发送appkey和trd_session数据，并对用户登录状态进行自动验证
*当islogin取值为false时，会默认只发送appkey，不对用户登录状态做任何验证，用于通用请求
*file_name文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容
*file_path为文件的微信临时路径
*/
function upload(path, data, file_name, file_path, islogin, fn) {
  var url = apps.globalData.adminUrl + path;
  var trd_session = apps.globalData.openUserInfo;
  data.appkey = apps.globalData.appKey;
  data.app_vision = apps.globalData.appVision;
  if (islogin) {
    if (loginFirst()) {
      data.trd_session = trd_session;
      wx.uploadFile({
        url: url,
        filePath: file_path,
        name:file_name,
        formData: data,
        success: function (res) {
            getResLogin(res.data);
            fn(res);
        },
        fail: function (res) {
          //调用接口失败或回传失败
          wx.showModal({
            title: '服务器繁忙',
            content: '网络不稳定，请稍后再试！',
            success: function (res) {
              if (res.confirm) {
                wx.switchTab({
                  url: '/pages/Personal/index/index'
                })
              }
            }
          })
        },
      })
    }
  }else{
    wx.uploadFile({
      url: url,
      filePath: file_path,
      name:file_name,
      formData: data,
      success: function (res) {
          getRes(res.data);
          fn(res);
      },
      fail: function (res) {
        //调用接口失败或回传失败
        wx.showModal({
          title: '服务器繁忙',
          content: '网络不稳定，请稍后再试！',
          success: function (res) {
            if (res.confirm) {
              wx.switchTab({
                url: '/pages/Personal/index/index'
              })
            }
          }
        })
      },
    })
  } 
}
//多张图片上传(无已存id)
function uploadimgs(data, dat, islogin,fn) {
  var that = this;
  var url = apps.globalData.adminUrl + dat.url;
  var trd_session = apps.globalData.openUserInfo;
  data.appkey = apps.globalData.appKey;
  data.app_vision = apps.globalData.appVision;
  if (islogin) {
    if (loginFirst()) {
      data.trd_session = trd_session;
      var i = dat.i ? dat.i : 0,//当前上传的哪张图片
        success = dat.success ? dat.success : 0,//上传成功的个数
        fail = dat.fail ? dat.fail : 0;//上传失败的个数
      wx.uploadFile({
        url: url,
        filePath: dat.path[i],
        name: 'img_info',//这里根据自己的实际情况改
        formData: data,
        success: (resp) => {
          fn(resp);
          success++;//图片上传成功，图片上传成功的变量+1
          i++;//这个图片执行完上传后，开始上传下一张
          if (i == dat.path.length) {   //当图片传完时，停止调用          
            console.log('成功：' + success + " 失败：" + fail);
          } else {//若图片还没有传完，则继续调用函数
            dat.i = i;
            dat.success = success;
            dat.fail = fail;
            that.uploadimgs(data, dat, islogin, fn);
          }
          //这里可能有BUG，失败也会执行这里,所以这里应该是后台返回过来的状态码为成功时，这里的success才+1
        },
        fail: (res) => {
          fail++;//图片上传失败，图片上传失败的变量+1
          console.log('fail:' + i + "fail:" + fail);
        },
        complete: () => {
        }
      });
    }
  }else{
    var i = dat.i ? dat.i : 0,//当前上传的哪张图片
       success = dat.success ? dat.success : 0,//上传成功的个数
       fail = dat.fail ? dat.fail : 0;//上传失败的个数
    wx.uploadFile({
      url: url,
      filePath: dat.path[i],
      name: 'img_info',//这里根据自己的实际情况改
      formData: data,
      success: (resp) => {
        fn(resp)
        success++;//图片上传成功，图片上传成功的变量+1
        i++;//这个图片执行完上传后，开始上传下一张
        if (i == dat.path.length) {   //当图片传完时，停止调用          
          console.log('成功：' + success + " 失败：" + fail);
        }else {//若图片还没有传完，则继续调用函数
          dat.i = i;
          dat.success = success;
          dat.fail = fail;
          that.uploadimgs(data, dat, fn);
        }
        //这里可能有BUG，失败也会执行这里,所以这里应该是后台返回过来的状态码为成功时，这里的success才+1
      },
      fail: (res) => {
        fail++;//图片上传失败，图片上传失败的变量+1
        console.log('fail:' + i + "fail:" + fail);
      },
      complete: () => {
      }
    });
  }
  
   
}

/*
*封装微信支付接口
*payment为后端传回的支付封装数据
*fn为支付成功返回函数
*/
 function payment(payment,fn){
// 	//判断支付状态开启
// 	if(payment.status=='success'){
		wx.requestPayment({
	    'timeStamp': payment.timeStamp,
	    'nonceStr': payment.nonceStr,
	    'package': payment.package,
	    'signType': payment.signType,
	    'paySign': payment.paySign,
	    'success': function (res) {
	      //提示 并跳转
	      fn(res);
	    },
	
	    'fail': function (res) {
        console.log(res);
	      wx.showModal({
	        title: '提示',
	        content: '支付失败，请重试',
	        showCancel: false
	      })
	    },
      'complete':function(res){
        console.log(res);
      }
	  })
	// }else{
	// 	wx.showModal({
	//         title: '系统维护',
	//         content: '系统正在维护，暂停支付，请稍后重试！',
	//         showCancel: false
	//       })
	// }
  

}

/*************************/
/*****自写组件模块集成******/
/*************************/

/*
*页面加载动态图片显示,用于统一化页面加载动图样式
*that参数为必选，取值为this
*width参数为可选，取值为动图宽度数值，数据类型为整型
*/
function overload(that,width) {
  width = width || 300; 
  that.setData({
    item: {
      dispaly: 'block',
      src: '../../img/loading.gif',
      width: width+'rpx'
    }
  })
}

/*
*页面加载动图隐藏
*that参数为必选，取值为this
*/
function overhide(that){
  that.setData({
    item: {
      dispaly: 'none'
    }
  })
}

/*
*图文混排模块封装函数
*/
function imgtext(content){ 
  var mode1 = /<img(?:.|\s)*?src=("|')(.*?)("|')(?:.|\s)*?><br(?:.|\s)*?>/gi;
  var mode2 = /(<br(?:.|\s)*?>)+/gi;
  var mode3 = /<(?:.|\s)*?>/g;
  content = content.replace(mode1, "(imgpartsss)$2(imgpartsss)");
  content = content.replace(mode2, "\n");
  content = content.replace(mode3, "");
  var strs = new Array(); //定义一数组 
  strs = content.split("(imgpartsss)");
  var results = new Array();
  for (var i = 0; i < strs.length; i++){
    if (i % 2 == 0) {
      if (trim(strs[i])){
        var team = new Object();
        team.types = 'txt';
        team.info = trim(strs[i]);
        results.push(team);
      }
    }else{
      var team = new Object();
      team.types = 'pic';
      team.info = strs[i];
      results.push(team);
    }
  }
  return results;
}

function trim(str) {
  return str.replace(/(^\s*)|(\s*$)/g, "");
} 

//工具类输出
module.exports.nav = nav;
module.exports.request = request;
module.exports.up = upload;
module.exports.uploadimgs = uploadimgs;
module.exports.login = login; 
module.exports.toast = toast;
module.exports.pay = payment; 

//模块类输出
module.exports.over = overload;
module.exports.hide = overhide;
module.exports.txt = imgtext;


//系统输出类
module.exports.loginOut = loginOut;

//系统工具类
module.exports.sdk = sdk;


/*************************/
/*****系统验证相关封装******/
/*************************/
//退出登录
function loginOut() {
  apps.globalData.openUserInfo = '';
  apps.globalData.user_openinfo = '';
  try {
    wx.removeStorageSync('local_user_session')
  } catch (e) {
    // Do something when catch error
  }
  wx.showToast({
    title: '退出成功',
    icon: 'success',
    duration: 1000
  })
  return true;
}
//登陆失效失效
function loginExpired() {
  apps.globalData.openUserInfo = '';
  apps.globalData.user_openinfo = '';
  try {
    wx.removeStorageSync('local_user_session');
    wx.showModal({
      title: '登录失效',
      content: '请重新登录',
      showCancel: false,
      success: function (res) {
        if (res.confirm) {
          login('', (res) => {
            //登录成功后的业务逻辑
            wx.setStorageSync('local_user_session', res.data.trd_session);
            apps.globalData.openUserInfo = res.data.trd_session;
            apps.globalData.user_openinfo = res.data.user_info;
            wx.showToast({
              title: '已登录成功',
              duration: 2000
            });
            wx.switchTab({
              url: '/pages/Personal/index/index'
            })
          });
          
        }
      }
    })
  } catch (e) {
    // Do something when catch error
  }
  
}

//提示登陆
function loginFirst() {
  
  if (apps.globalData.openUserInfo == '') {
    console.log(apps.globalData.openUserInfo)
    console.log(184)
    wx.showModal({
      title: '未登录',
      content: '请您先登录',
      success: function (res) {
        if (res.confirm) {
          login('', (res) => {
            //登录成功后的业务逻辑
            wx.setStorageSync('local_user_session', res.data.trd_session);
            apps.globalData.openUserInfo = res.data.trd_session;
            apps.globalData.user_openinfo = res.data.user_info;
            wx.showToast({
              title: '已登录成功',
              duration: 2000
            });
            wx.switchTab({
              url: '/pages/Personal/index/index'
            })
          });
        }
      }
    })
    return false;
  } else {
    return true;
  }

}

//判断小程序状态
function getRes(res) {
  if (res.state == 'ERROR') {
    wx.navigateTo({
      url: '/pages/Home/error/error?title=小程序出错啦！&content=请联系小程序运营者！'
    })
    return;
  } else if (res.state == 'TIMEOUT') {
    wx.navigateTo({
      url: '/pages/Home/error/error?title=小程序出错啦！&content=请您联系小程序运营者！'
    })
    return;
  } else {
    //不做任何动作
  }
}

//判断小程序状态和登录状态
function getResLogin(res) {
  if (res.state == 'ERROR') {
    wx.navigateTo({
      url: '/pages/Home/error/error?title=小程序出错啦！&content=请联系小程序运营者！'
    })
    return;
  } else if (res.state == 'TIMEOUT') {
    wx.navigateTo({
      url: '/pages/Home/error/error?title=小程序出错啦！&content=请您联系小程序运营者！'
    })
    return;
  } else if (res.state == 'Login_Expired') {
    loginExpired();
    return;
  } else {
    //不做任何动作
  }
}


/*************************/
/*****系统基础库相关******/
/*************************/

//判断用户基础库版本是否满足要求
function sdk(vision){
  var system = wx.getSystemInfoSync();
  var sys_sdk = system.SDKVersion;
  var sdks = new Array(); 
  var visions = new Array(); 
  sdks = sys_sdk.split("."); 
  visions = vision.split("."); 
  if (parseInt(visions[0]) < parseInt(sdks[0])){
       return true;
  } else if (parseInt(visions[0]) == parseInt(sdks[0])){
    if (parseInt(visions[1]) < parseInt(sdks[1])){
      return true;
    } else if (parseInt(visions[1]) == parseInt(sdks[1])){
      if (parseInt(visions[2]) <= parseInt(sdks[2])){
        return true;
      }else{
        return false;
      }
    }else{
      return false;
    }
  }else{
    return false;
  }
}